package com.usoft;


import akka.dispatch.ExecutionContexts;
import akka.dispatch.Futures;
import akka.dispatch.OnSuccess;
import akka.japi.Function2;
import scala.concurrent.ExecutionContextExecutorService;
import scala.concurrent.Future;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;


/**
 * Futures.fold
 * Created by liyanxin on 2015/1/9.
 */
public class ComposeFuture3 {

    public static void main(String args[]) {

        final ExecutionContextExecutorService ec = ExecutionContexts.
                fromExecutorService(Executors.newCachedThreadPool());

        List<Future<String>> listOfFutureInts = new ArrayList<Future<String>>(10);
        for (int i = 0; i < 10; i++) {
            Future<String> item = Futures.successful(String.valueOf(i));
            listOfFutureInts.add(item);
        }

        //Start value is the empty string
        Future<String> resultFuture = Futures.fold("", listOfFutureInts,
                new Function2<String, String, String>() {
                    @Override
                    public String apply(String arg1, String arg2) throws Exception {
                        return arg1 + arg2;
                    }
                }, ec);
        resultFuture.onSuccess(new OnSuccess<String>() {
            @Override
            public void onSuccess(String result) throws Throwable {
                System.out.println(result);
            }
        }, ec);
    }
}
